// packageA/pages/notWorkAdd/notWorkAdd.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:{},
    //表单信息
    editInfo:{
      date: util.timeFormat(new Date()),
      dateStr: util.timeFormatDay(new Date()),
    },
    //传参来的id
    id:null,
    //是否是修改
    isEdit:false,
    //提交按钮禁用
    disabled:false,
    //避免表单重复提交
    code:null, 
    //设备信息
    equipmentInfo:null,
    //日期选择框
    showDate:false,    
    //当前时间
    current: new Date().getTime(),
    //最大时间
    maxDate: new Date().getTime(),   
    //时间格式
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      }
      return value
    },
    //上传路径
    ossUploadUrl: app.globalData.ossUrl
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.getUserProfile({
      desc: '为您提供更好的服务',
      success: (res) => {}
    })
    
    this.setData({
      code:Base64.encode(new Date() + app.globalData.userInfo.userName)
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('不工作上报传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id,
          isEdit:true
        })
        //获取修改的数据
        this.getInfo();
      }

      //获取设备信息
      this.getEquipmentInfo();
    }
  },

  //获取设备信息
  getEquipmentInfo(){
    let param = {
      isAuth: false,
      className: 'equipment',
      data: {
        id: this.data.paramObj.equipmentId,
        selectFields: ['id','memberId','regionId','project','dataAuthority']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result[0];
        this.setData({
          equipmentInfo: result
        })
      }
    }).catch((error) => {
    })
  },  

  //显示日期
  onShowDate(){
    this.setData({
		  showDate: true
    })
  },

  //隐藏日期
  onCloseDate(){
    this.setData({
		  showDate: false
    })
  },

  //确认日期
  onConfirmDate(e) {
    let dd='editInfo.date';
    let dd2='editInfo.dateStr';

    this.setData({
      current: e.detail,      
      [dd]: util.timeFormat(e.detail),
      [dd2]: util.timeFormatDay(e.detail)
    })

    this.onCloseDate();
  },

  //获取图片上传组件的传值
  getUploadUrl(data){
    let imgUrls=data.detail;
    let pic='editInfo.pic';

    if(imgUrls.length){
      this.setData({
        [pic]: imgUrls
      })
    }
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let obj = {};
    obj['disabled'] = false;
    this.setData(obj);
  },

  //提交表单
  confirmForm(e){
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let td=this.data;
    let editInfo=td.editInfo;  
    let user=app.globalData.userInfo;
    let equipmentInfo=td.equipmentInfo;

    //原因必填
    let reason=obj.reason.trim();
    if(!reason){
      Toast.fail('请输入原因');
      return;
    }  

    let param={
      className:'equipmentNotWorkReason',
      data:{
        requestToken: td.code,
        id: td.id,
        date:editInfo.date,
        dateStr:editInfo.dateStr,
        reason: reason,
        imei: td.paramObj.imei,
        equipmentNo: td.paramObj.equipmentNo,
        pic: editInfo.pic,
        memberId: equipmentInfo.memberId ? equipmentInfo.memberId : null,
        regionId: equipmentInfo.regionId ? equipmentInfo.regionId : null,
        project: equipmentInfo.project ? equipmentInfo.project : null,
        dataAuthority: equipmentInfo.dataAuthority  
      }
    }

    if(!td.isEdit){
      param.data.user={
        id:user.id,
        name:user.userName,
        phone:user.personalPhone
      }
    }

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    //console.log(param.data);

    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    }) 
  },

  //获取修改的数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'equipmentNotWorkReason',
      data: {
        id:this.data.id,
        selectFields: ['id','date','dateStr','reason','pic']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];
        console.log('上报信息回显');
        console.log(result);

        this.setData({
          editInfo: result
        })
      }
    }).catch((error) => {
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})